package com.shuqi.model.manager;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.HashSet;
import java.util.List;

import org.apache.http.message.BasicNameValuePair;

import android.content.Context;
import android.text.TextUtils;

import com.shuqi.application.ShuqiApplication;
import com.shuqi.common.Config;
import com.shuqi.common.Constant;
import com.shuqi.common.XOREncryptUncrypt;
import com.shuqi.common.utils.BookContentUtils;
import com.shuqi.common.utils.Log4an;
import com.shuqi.common.utils.Util;
import com.shuqi.controller.R;
import com.shuqi.database.dao.impl.BookCataLogDao;
import com.shuqi.database.dao.impl.BookInfoDao;
import com.shuqi.database.model.BookCataLog;
import com.shuqi.database.model.BookInfo;
import com.shuqi.database.model.BookMarkInfo;
import com.shuqi.interfaces.EventTypeConstants;
import com.shuqi.model.bean.BookChapterOssInfo;
import com.shuqi.model.bean.ChapterInfo;
import com.shuqi.model.manager.BookCatalogManager.ShuqiOneChapterData;
import com.shuqi.model.net.HttpRequest;
import com.shuqi.model.net.listener.HttpRequestListener;
import com.shuqi.model.parse.parser.ChapterContentCdnParser;

/**
 * 书旗章节下载、全本下载；神马章节下载，全本下载 读写章节内容
 * 
 * @author zhangpeng
 * 
 */
public class DownLoadBookManager {
    private static String TAG = "DownLoadBookManager";
    public static final String CHAPTER_FILE_SUFFIX = ".sqc";

    public static final int DOWNLOADBOOK_MANAGER_RESULTYPE_NETNORMAL = 0;
    public static final int DOWNLOADBOOK_MANAGER_RESULTYPE_NETERROR = 1;

    public static interface OneChapterCallback {
        public void onOneChapter(ChapterInfo chapterInfo);
    }

    // ------------------书籍章节内容相关功能------------------------
    public static final int DOWNLOAD_ERROR = -1;
    public static final int CATALOG_DOWNLOAD_ERROR = -2;
    public static final int DECODE_ERROR = -3;
    public static final int NEED_BUY_ERROR = -4;
    public static final int BOOK_HIDE_ERROR = -5;
    public static final int NO_NET = -7;
    public static final int BOOK_OFFSHELF = 9;


    /**
     * 阅读页获取章节内容 (先下载一章 回调)
     * 
     * @param context
     * @param sourceId
     * @param bookId
     * @param cid
     * @param needBuy
     * @param uid
     * @param callBack
     * @return
     */
    public static ChapterInfo getCurChapterInfo(Context context, String sourceId, String bookId,
            String cid, boolean needBuy, String uid, OneChapterCallback callBack) {
        return getCurInfo(context, sourceId, bookId, cid, needBuy, uid, callBack);
    }


    /**
     * 阅读页获取章节内容 各种异常提示 ...... 2 书豆不足 -1 下载失败 -2 获取目录失败 -3 解码失败 -4 需要购买 -5 书籍已被关闭 -6阅读已被关闭 9 下架书籍
     * 
     * @param context applicationcontext
     * @param bookId 当前书籍bid
     * @param oid 当前章节oid
     * @param cid 当前章节cid
     * @param needBuy 是否需要购买:不勾选上，true；勾选false
     * @param uid 用户id
     * @return
     */
    private static ChapterInfo getCurInfo(Context context, String sourceId, String bookId,
            String cid, boolean needBuy, String uid, OneChapterCallback callBack) {
        if (context == null || TextUtils.isEmpty(bookId) || TextUtils.isEmpty(cid)
                || "0".equals(cid)) {
            return null;
        }
        uid = TextUtils.isEmpty(uid) ? Constant.GUEST_USER_ID : uid;
        ChapterInfo chapterInfo = new ChapterInfo();
        chapterInfo.setBookId(bookId);
        chapterInfo.setUid(uid);
        // Log4an.e("yjd", "【getCurInfo】uid=" + uid + ",bookId=" + bookId + ",cid=" + cid
        // + ",sourceId=" + sourceId);
        BookCataLog info =
                BookCataLogDao.getInstance().getBookCatalogByCid(uid, bookId, sourceId, cid);
        // Log4an.e("yjd", "【getCurInfo】info is null =" + (info == null ? true : false));
        BookInfo mbookInfo = BookInfoDao.getInstance().getBookInfo(sourceId, bookId, uid);

        final boolean isUpsdate =
                mbookInfo == null ? false
                        : mbookInfo.getUpdateCatalog() == BookInfo.UPDATE_CATALOG_YES;
        // Log4an.i("yjd", "uid=" + uid + ", bookId=" + bookId + ", isUpsdate=" + isUpsdate);
        int oid = 1;
        if (info != null && !isUpsdate) {
            oid = info.getOId();
            // Log4an.i("yjd", "【章节名称】" + info.getChapterName());
            if (callBack != null) {
                callBack.onOneChapter(null);
            }
        } else {
            // Log4an.e("yjd", "callBack is null =" + (callBack == null ? true : false));
            if (callBack != null) {
                // 获取一章的目录信息
                BookCataLog cataLog = null;
                ShuqiOneChapterData sqOneChapterData = null;
                if (sourceId == null) {
                    sqOneChapterData = BookCatalogManager.downloadShuqiOneChapter(bookId, uid, cid);
                    if (sqOneChapterData != null && sqOneChapterData.boCataLog != null) {
                        cataLog = sqOneChapterData.boCataLog;
                    }
                } else {
                    cataLog =
                            BookCatalogManager.downloadYiSouOneChapter(bookId, sourceId, uid, cid);
                }
                // Log4an.e("yjd", "【getCurInfo】cataLog is null =" + (cataLog == null ? true :
                // false));
                // 下载一章的正文信息
                if (cataLog != null) {
                    ChapterInfo oneChapterInfo = new ChapterInfo();
                    oneChapterInfo.setBookId(bookId);
                    oneChapterInfo.setUid(uid);
                    oneChapterInfo.setCurChapterCid(cataLog.getChapterId());
                    oneChapterInfo.setCurChapterName(cataLog.getChapterName());
                    oneChapterInfo.setCurChapterVid(cataLog.getVolumeId());
                    oneChapterInfo.setCurChapterPaid(String.valueOf(cataLog.getPayState()));
                    oneChapterInfo.setCurChapterPayMode(String.valueOf(cataLog.getPayMode()));
                    oneChapterInfo.setCurChapterPrice(cataLog.getChapterPrice());
                    oneChapterInfo.setCurChapterWordCount(String.valueOf(cataLog
                            .getChapterWordCount()));
                    oneChapterInfo.setCurDownload(cataLog.getDownloadState());
                    boolean contentResult =
                            getChapterContent(context, oneChapterInfo, bookId, sourceId, uid, cid,
                                    needBuy, cataLog.getChapterContentUrl());
                    // Log4an.e(TAG, "1.contentResult=" + contentResult);
                    if (contentResult) {
                        callBack.onOneChapter(oneChapterInfo);
                    }
                } else {
                    if (Util.isNetworkConnected(context)) {
                        if (sqOneChapterData != null) {
                            if ("Y".equals(sqOneChapterData.hide)) {
                                chapterInfo.setCurChapterType(BookContentUtils.TYPE_BOOK_CLOSED);
                                chapterInfo.setMsg(context.getResources().getString(
                                        R.string.book_close));
                                return chapterInfo;
                            } else if (0 == sqOneChapterData.readIsopen) {
                                chapterInfo.setCurChapterType(BookContentUtils.TYPE_READ_CLOSED);
                                chapterInfo.setMsg(context.getResources().getString(
                                        R.string.bookcontent_close));
                                return chapterInfo;
                            } else {
                                if (Util.isNetworkConnected(context)) {
                                    handleError(chapterInfo, CATALOG_DOWNLOAD_ERROR);
                                } else {
                                    handleError(chapterInfo, NO_NET);
                                }
                            }
                        } else {
                            if (Util.isNetworkConnected(context)) {
                                handleError(chapterInfo, CATALOG_DOWNLOAD_ERROR);
                            } else {
                                handleError(chapterInfo, NO_NET);
                            }
                        }

                    } else {
                        handleError(chapterInfo, NO_NET);
                    }
                }
            }

            // 下载整个目录
            if (sourceId == null) {
                // Log4an.e("yjd", "【下载整个目录】bookId=" + bookId + ",uid=" + uid + ",sourceId="
                // + sourceId);
                BookCatalogManager.syncDownloadCatalog(bookId, sourceId, uid,
                        BookMarkInfo.TYPE_NEW_PAY_BOOKMARK, null);
            } else {
                BookCatalogManager.syncDownloadCatalog(bookId, sourceId, uid,
                        BookMarkInfo.TYPE_NEW_SHENMA_BOOKMARK, null);
            }
            // Log4an.e("yjd", "2.【getCurInfo】uid=" + uid + ",bookId=" + bookId + ",cid=" + cid
            // + ",sourceId=" + sourceId);
            info = BookCataLogDao.getInstance().getBookCatalogByCid(uid, bookId, sourceId, cid);
            // Log4an.e("yjd", "2.【getCurInfo】info is null =" + (info == null ? true : false));
            if (info != null) {
                oid = info.getOId();
            } else {
                if (Util.isNetworkConnected(context)) {
                    handleError(chapterInfo, CATALOG_DOWNLOAD_ERROR);
                } else {
                    handleError(chapterInfo, NO_NET);
                }
                return chapterInfo;
            }
        }
        int pageSize = 3;
        int curIndex = 1;// 当前章索引
        int startOid = oid - 1;// 从上一章开始获取
        if (startOid <= 0) {// 无上一章
            startOid = 1;
            pageSize = 2;
            curIndex = 0;
        }

        BookInfo bookInfo = BookInfoDao.getInstance().getBookInfo(sourceId, bookId, uid);
        // 获取目录信息
        List<BookCataLog> cataLogList =
                BookCataLogDao.getInstance().getBookCatalogListFromChapterIndex(uid, bookId,
                        sourceId, startOid, pageSize + 4);

        if (bookInfo == null || cataLogList == null || cataLogList.size() <= 0) {
            if (Util.isNetworkConnected(context)) {
                handleError(chapterInfo, CATALOG_DOWNLOAD_ERROR);
            } else {
                handleError(chapterInfo, NO_NET);
            }
            return chapterInfo;
        }
        boolean statusResult = statusCheck(context, chapterInfo, bookInfo);
        if (!statusResult) {
            return chapterInfo;
        }

        BookCataLog catalogInfo = null;
        for (int i = 0; i < cataLogList.size() && i < pageSize; i++) {
            catalogInfo = cataLogList.get(i);
            if (oid == catalogInfo.getOId()) {// 当前章
                chapterInfo.setCurChapterCid(catalogInfo.getChapterId());
                chapterInfo.setCurChapterName(catalogInfo.getChapterName());
                chapterInfo.setCurChapterOid(oid);
                chapterInfo.setCurChapterVid(catalogInfo.getVolumeId());
                chapterInfo.setCurChapterPaid(String.valueOf(catalogInfo.getPayState()));
                chapterInfo.setCurChapterPayMode(String.valueOf(catalogInfo.getPayMode()));
                chapterInfo.setCurChapterPrice(catalogInfo.getChapterPrice());
                chapterInfo
                        .setCurChapterWordCount(String.valueOf(catalogInfo.getChapterWordCount()));
                chapterInfo.setCurDownload(catalogInfo.getDownloadState());
            } else {
                if (i == 0) {// 上一章
                    chapterInfo.setPreChapterCid(catalogInfo.getChapterId());
                    chapterInfo.setPreChapterOid(catalogInfo.getOId());
                    chapterInfo.setPreChapterName(catalogInfo.getChapterName());
                    chapterInfo.setPreChapterPaid(String.valueOf(catalogInfo.getPayState()));
                    chapterInfo.setPreChapterPayMode(String.valueOf(catalogInfo.getPayMode()));
                    chapterInfo.setPreChapterPrice(catalogInfo.getChapterPrice());
                    chapterInfo.setPreChapterWordCount(String.valueOf(catalogInfo
                            .getChapterWordCount()));
                } else if (i == 1 || i == 2) {// 下一章
                    chapterInfo.setNextChapterCid(catalogInfo.getChapterId());
                    chapterInfo.setNextChapterOid(catalogInfo.getOId());
                    chapterInfo.setNextChapterName(catalogInfo.getChapterName());
                    chapterInfo.setNextChapterPaid(String.valueOf(catalogInfo.getPayState()));
                    chapterInfo.setNextChapterPayMode(String.valueOf(catalogInfo.getPayMode()));
                    chapterInfo.setNextChapterPrice(catalogInfo.getChapterPrice());
                    chapterInfo.setNextChapterWordCount(String.valueOf(catalogInfo
                            .getChapterWordCount()));
                }
            }
        }

        boolean contentResult =
                getChapterContent(context, chapterInfo, bookId, sourceId, uid, cid, needBuy, null);
        // Log4an.e(TAG, "2.contentResult=" + contentResult);
        if (!contentResult) {
            return chapterInfo;
        }

        // 缓存后续章节
        HashSet<String> set = new HashSet<String>();
        for (int i = curIndex + 1; i < cataLogList.size(); i++) {
            // 如果是免费章节或者已付费则可以缓存
            if (Constant.PAYMODE_FREE == cataLogList.get(i).getPayMode()
                    || Constant.PAYMODE_BOOK_FREE == cataLogList.get(i).getPayMode()// 全本免费的章节
                    || BookCataLog.HAS_PAY == cataLogList.get(i).getPayState()) {
                set.add(cataLogList.get(i).getChapterId());
            }
        }
        if (set.size() > 0) {
            set = BookCataLogDao.getInstance().getNeedDownLoadCidSet(uid, sourceId, bookId, set);
            if (set != null && set.size() > 0) {
                CacheChapters.getInstance().notifyCacheBook(sourceId, bookId, uid, set);
            }

        }
        return chapterInfo;
    }

    /**
     * 神马和书旗章节下载
     * 
     * @param context
     * @param sourceId
     * @param bookId
     * @param cid
     * @param uid
     * @return
     */
    public static String downChapter(Context context, String sourceId, final String bookId,
            final String cid, final String uid) {
        if (context == null || TextUtils.isEmpty(bookId) || TextUtils.isEmpty(uid)) {
            throw new IllegalArgumentException("bookId is null or uid is illegal");
        }
        String chapterContent = null;
        // 获取对应目录章节cdn地址
        BookCataLog catalogInfo =
                BookCataLogDao.getInstance().getBookCatalogByCid(uid, bookId, sourceId, cid);
        if (catalogInfo != null) {
            // 下载章节内容
            if (sourceId == null) {
                List<String> chapterContents =
                        DownLoadBookManager.loadPayChapterContent(context,
                                catalogInfo.getChapterContentUrl());
                if (chapterContents != null && chapterContents.size() > 0) {
                    chapterContent = chapterContents.get(0);
                }
            } else {
                if (!TextUtils.isEmpty(catalogInfo.getChapterContentUrl())) {
                    BookChapterOssInfo loadYiSouChapterContent =
                            DownLoadBookManager.loadYiSouChapterContent(context,
                                    catalogInfo.getChapterContentUrl());
                    chapterContent =
                            loadYiSouChapterContent == null ? null : loadYiSouChapterContent
                                    .getText();
                }
            }

            if (chapterContent != null && !"".equals(chapterContent)) {

                DownLoadBookManager.writeChapterFile(sourceId, bookId, uid, cid, chapterContent);
                // 更新数据库下载状态
                BookCataLogDao.getInstance().updateCatalogToDown(bookId, sourceId, uid, cid);
                int count = (int) BookCataLogDao.getInstance().getChapterDownLoadCount(uid, bookId);
                // 更新书籍信息--总下载章节数量
                if (count > 0) {
                    BookInfo bookInfo = new BookInfo();
                    bookInfo.setSourceId(sourceId);
                    bookInfo.setBookId(bookId);
                    bookInfo.setUserId(uid);
                    bookInfo.setBookDownCount(count);
                    BookInfoDao.getInstance().saveOrUpdateBookInfo(bookInfo);
                }
            }
        }
        return chapterContent;
    }

    /**
     * 书旗章节下载
     * 
     * @return
     */
    public static List<String> loadPayChapterContent(Context context, String chapterUrl) {
        if (context == null || TextUtils.isEmpty(chapterUrl)) {
            Log4an.e(TAG, "[loadPayChapterContent]context==null或 chapterUrl==null");
            return null;
        }
        final PayChaptersContentBean bean = new PayChaptersContentBean();
        HttpRequestListener httpRequsetListener = new HttpRequestListener() {

            @SuppressWarnings("unchecked")
            @Override
            public void action(int actionCode, Object object) {
                if (actionCode == EventTypeConstants.EVENT_SUCCESS) {
                    bean.chaptersContent = (List<String>) object;
                } else {// 否则通知失败
                    Log4an.d(TAG, "【loadPayChapterContent】buyBookOnline err,code=" + actionCode);
                }
            }

            @Override
            public List<BasicNameValuePair> setParams() {
                return null;
            }

            @Override
            public String getRequestUrl() {
                Log4an.d(TAG, "【loadPayChapterContent】getRequestUrl is null");
                return null;
            }

        };
        if (context == null || TextUtils.isEmpty(chapterUrl)) {
            Log4an.e(TAG, "[PayHttpRequest]context==null或 chapterUrl==null");
            return null;
        }
        HttpRequest request = new HttpRequest(context, chapterUrl, false, httpRequsetListener);
        request.setDataParseAdapter(new ChapterContentCdnParser(context));
        request.run();
        return bean.chaptersContent;
    }

    /**
     * 一搜章节下载
     * 
     * @return
     */
    public static BookChapterOssInfo loadYiSouChapterContent(Context context, String chapterUrl) {
        if (context == null || TextUtils.isEmpty(chapterUrl)) {
            Log4an.e(TAG, "[loadYiSouChapterContent]context==null或 chapterUrl==null");
            return null;
        }
        final YiSouChaptersContentBean bean = new YiSouChaptersContentBean();
        HttpRequestListener httpRequsetListener = new HttpRequestListener() {

            @Override
            public void action(int actionCode, Object object) {
                if (actionCode == EventTypeConstants.EVENT_SUCCESS) {
                    bean.chaptersContent = (BookChapterOssInfo) object;
                } else {// 否则通知失败
                    Log4an.d(TAG, "【loadYiSouChapterContent】buyBookOnline err,code=" + actionCode);
                }
            }

            @Override
            public List<BasicNameValuePair> setParams() {
                return null;
            }

            @Override
            public String getRequestUrl() {
                Log4an.d(TAG, "【loadYiSouChapterContent】getRequestUrl is null");
                return null;
            }

        };
        if (context == null || TextUtils.isEmpty(chapterUrl)) {
            Log4an.e(TAG, "[YiSouHttpRequest]context==null或 chapterUrl==null");
            return null;
        }
        // Log4an.d(TAG, "【loadYiSouChapterContent】chapterUrl=" + chapterUrl);
        HttpRequest request = new HttpRequest(context, chapterUrl, true, httpRequsetListener);
        request.run();
        return bean.chaptersContent;
    }

    /**
     * 一搜章节内容内部类
     * 
     * @author zhangpeng
     * 
     */
    private static class YiSouChaptersContentBean {
        public BookChapterOssInfo chaptersContent;
    }

    /**
     * 书旗章节内容内部类
     * 
     * @author zhangpeng
     * 
     */
    private static class PayChaptersContentBean {
        public List<String> chaptersContent;
    }

    /**
     * 读取章节缓存文件
     */
    public static String readChapterFile(String sourceId, String bookId, String uid, String cid) {
        File file = null;
        if (sourceId != null) {
            file =
                    new File(Config.DEFAULT_YISOU_CHAPTER_CACHE_PATH + uid + "/" + sourceId + "/"
                            + bookId + "/" + cid + CHAPTER_FILE_SUFFIX);
        } else {
            file =
                    new File(Config.DEFAULT_SHUQI_CHAPTER_CACHE_PATH + uid + "/" + bookId + "/"
                            + cid + CHAPTER_FILE_SUFFIX);
        }
        Log4an.e("yjd", "getAbsolutePath=" + file.getAbsolutePath());
        if (!file.exists()) {
            return null;
        }
        FileInputStream is = null;
        BufferedInputStream bis = null;
        try {
            is = new FileInputStream(file);
            bis = new BufferedInputStream(is);
            byte[] bytes = Util.getBytes(bis);
            XOREncryptUncrypt.encryptAndUncrypt(bytes, uid.charAt(uid.length() - 1));
            return new String(bytes, "UTF-8");
        } catch (Exception e) {
        } finally {
            if (is != null) {
                try {
                    is.close();
                } catch (Exception e) {
                }
            }
            if (bis != null) {
                try {
                    bis.close();
                } catch (Exception e) {
                }
            }
        }

        return null;
    }


    /**
     * 写入文件
     * 
     * @param sourceId
     * @param bookId
     * @param uid
     * @param cid
     * @param chapterContent
     * @return
     */
    public static boolean writeChapterFile(String sourceId, String bookId, String uid, String cid,
            String chapterContent) {
        File dir = null;
        if (sourceId != null) {
            dir =
                    new File(Config.DEFAULT_YISOU_CHAPTER_CACHE_PATH + uid + "/" + sourceId + "/"
                            + bookId + "/");
        } else {
            dir = new File(Config.DEFAULT_SHUQI_CHAPTER_CACHE_PATH + uid + "/" + bookId + "/");
        }
        if (!dir.exists()) {
            dir.mkdirs();
        }
        File file = new File(dir, cid + CHAPTER_FILE_SUFFIX);
        if (!file.exists()) {
            try {
                file.createNewFile();
            } catch (Exception e) {
                Log4an.e(TAG, "writeChapterFile createNewFile err:" + file.getAbsolutePath());
                return false;
            }
        }
        FileOutputStream os = null;
        BufferedOutputStream bos = null;
        try {
            os = new FileOutputStream(file);
            bos = new BufferedOutputStream(os);
            byte[] bytes = chapterContent.getBytes("UTF-8");
            XOREncryptUncrypt.encryptAndUncrypt(bytes, uid.charAt(uid.length() - 1));
            bos.write(bytes);
            bos.flush();
            return true;
        } catch (Exception e) {
        } finally {
            if (os != null) {
                try {
                    os.close();
                } catch (Exception e) {
                }
            }
            if (bos != null) {
                try {
                    bos.close();
                } catch (Exception e) {
                }
            }
        }

        return false;
    }

    /**
     * 获取当前章节正文内容
     * 
     * @param chapterInfo
     * @param bookId
     * @param sourceId
     * @param uid
     * @param cid
     * @param needBuy
     * @return 获取成功返回truek
     */
    private static boolean getChapterContent(Context context, ChapterInfo chapterInfo,
            String bookId, String sourceId, String uid, String cid, boolean needBuy, String url) {
        String chapter = null;
        // Log4an.e("yjd", "【getChapterContent】cPayMode=" + chapterInfo.getCurChapterPayMode()
        // + ",cPaid=" + chapterInfo.getCurChapterPaid());
        // Log4an.e("yjd", "1.【getChapterContent】needBuy=" + needBuy);
        // Log4an.e("yjd", "getCurChapterPayMode=" + chapterInfo.getCurChapterPayMode()
        // + ",getCurChapterPaid=" + chapterInfo.getCurChapterPaid());
        if (String.valueOf(BookInfo.FREE).equals(chapterInfo.getCurChapterPayMode())// 免费的
                || String.valueOf(BookInfo.ALL_BOOK_FREE)
                        .equals(chapterInfo.getCurChapterPayMode())// 全本免费的章节
                || BookCataLog.HAS_DOWN == chapterInfo.getCurDownload()// 已下载的章节
                || String.valueOf(BookInfo.HAS_PAY).equals(chapterInfo.getCurChapterPaid())) {// 已付费的
            chapter = readChapterFile(sourceId, bookId, uid, cid);
        } else {
            // Log4an.e("yjd", "2.【getChapterContent】needBuy=" + needBuy);
            if (needBuy) {
                handleError(chapterInfo, NEED_BUY_ERROR);
                return false;
            } else {
                Log4an.e("yjd", "【buyChapterOnline】bookId=" + bookId + ",cid=" + cid + ",uid="
                        + uid);
                ChapterInfo tempInfo =
                        BuyBookManager.buyChapterOnline(ShuqiApplication.getContext(), bookId, cid,
                                uid, chapterInfo.getCurChapterPrice());
                if (tempInfo != null) {
                    chapterInfo.setCurChapterType(tempInfo.getCurChapterType());
                    if (!BookContentUtils.TYPE_HAS_READ.equals(chapterInfo.getCurChapterType())) {
                        if (BookContentUtils.TYPE_BOOK_SOLD_OUT.equals(chapterInfo
                                .getCurChapterType())) {
                            chapterInfo.setMsg("已下架，不可购买");
                        } else {
                            chapterInfo.setMsg(tempInfo.getCurChapterInfo());
                        }
                        return false;
                    }
                } else {
                    if (Util.isNetworkConnected(context)) {
                        handleError(chapterInfo, DOWNLOAD_ERROR);
                    } else {
                        handleError(chapterInfo, NO_NET);
                    }
                    return false;
                }
            }
        }
        // Log4an.d("yjd", "1.【getChapterContent】chapter=" + (chapter == null ? true : false)
        // + ",url=" + url);
        if (chapter == null) {
            if (TextUtils.isEmpty(url)) {
                // Log4an.d("yjd", "sourceId=" + sourceId + ",bookId=" + bookId + ",cid=" + cid);
                chapter = downChapter(ShuqiApplication.getContext(), sourceId, bookId, cid, uid);
            } else {
                if (TextUtils.isEmpty(sourceId)) {
                    List<String> strList =
                            loadPayChapterContent(ShuqiApplication.getContext(), url);
                    if (strList != null && strList.size() > 0) {
                        chapter = strList.get(0);
                    }
                } else {
                    BookChapterOssInfo info =
                            loadYiSouChapterContent(ShuqiApplication.getContext(), url);
                    chapter = info == null ? null : info.getText();
                }
            }
        }
        // Log4an.d("yjd", "2.【getChapterContent】chapter=" + chapter);
        if (chapter != null) {
            chapterInfo.setCurChapterType(BookContentUtils.TYPE_HAS_READ);
            chapterInfo.setCurChapterInfo(chapter);
            return true;
        } else {
            if (Util.isNetworkConnected(context)) {
                handleError(chapterInfo, DOWNLOAD_ERROR);
            } else {
                handleError(chapterInfo, NO_NET);
            }
            return false;
        }
    }

    /**
     * 书籍状态为检查
     * 
     * @param context
     * @param chapterInfo
     * @param bookInfo
     * @return 状态位关闭返回false
     */
    private static boolean statusCheck(Context context, ChapterInfo chapterInfo, BookInfo bookInfo) {
        if ("Y".equals(bookInfo.getBookStatus())) {
            chapterInfo.setCurChapterType(BookContentUtils.TYPE_BOOK_CLOSED);
            chapterInfo.setMsg(context.getResources().getString(R.string.book_close));
            return false;
        }
        if (0 == bookInfo.getReadHideState()) {
            chapterInfo.setCurChapterType(BookContentUtils.TYPE_READ_CLOSED);
            chapterInfo.setMsg(context.getResources().getString(R.string.bookcontent_close));
            return false;
        }
        return true;
    }


    /**
     * 错误信息处理
     * 
     * @param chapterInfo
     * @param errorCode
     */
    private static void handleError(ChapterInfo chapterInfo, int errorCode) {
        chapterInfo.setCurChapterType(String.valueOf(errorCode));
        switch (errorCode) {
            case DOWNLOAD_ERROR:
            case NO_NET:
                chapterInfo.setMsg("下载失败");
                break;
            case CATALOG_DOWNLOAD_ERROR:
                chapterInfo.setMsg("获取目录失败");
                break;
            case DECODE_ERROR:

                break;
            case NEED_BUY_ERROR:
                chapterInfo.setMsg("需要购买");
                break;
            case BOOK_HIDE_ERROR:
                chapterInfo.setMsg("关闭啦");
                break;
            // case READ_HIDE_ERROR:
            //
            // break;
            case BOOK_OFFSHELF:
                break;
            // case NO_NET:
            // chapterInfo.setMsg("网络不给力,请重试！");
            // break;
            default:
                break;
        }
    }

    /**
     * 检查一章的内容是否存在
     * 
     * @param bookId
     * @param sourceId
     * @param chapterId
     * @param uid
     * @return
     */
    public static boolean isContentExist(String bookId, String sourceId, String chapterId,
            String uid) {
        // 判断目录是否存在
        BookCataLog catalog =
                BookCataLogDao.getInstance().getBookCatalogByCid(uid, bookId, sourceId, chapterId);
        if (catalog == null) {
            return false;
        }
        File file = null;
        if (sourceId != null) {
            file =
                    new File(Config.DEFAULT_YISOU_CHAPTER_CACHE_PATH + uid + "/" + sourceId + "/"
                            + bookId + "/" + chapterId + CHAPTER_FILE_SUFFIX);
        } else {
            file =
                    new File(Config.DEFAULT_SHUQI_CHAPTER_CACHE_PATH + uid + "/" + bookId + "/"
                            + chapterId + CHAPTER_FILE_SUFFIX);
        }
        if (!file.exists()) {
            return false;
        }
        // 判断缓存文件是否存在
        return true;
    }
}
